﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace synjones.project.cas
{
    public partial class _Login : System.Web.UI.Page
    {
        public string InformationMessage = string.Empty;
        protected void Page_Load(object sender, EventArgs e)
        {
            InformationMessage = string.Empty;
            if (!this.IsPostBack)
            {
                if (Request["continue_url"] == null)
                    Response.Redirect("error.aspx");

                if ((Request.Cookies["synpay_cas_user"] != null) && (Request.Cookies["synpay_cas_data"] != null))
                {
                    doLogin(
                        Request.Cookies["synpay_cas_user"].Value,
                        Request.Cookies["synpay_cas_data"].Value,
                        Request["continue_url"]);
                }
            }
            else
            {
                string loginid = Request["loginid"];
                string password = Request["password"];
                string continute_url = Request["continue_url"];
                password = PasswordTools.EncryptPassword(password);
                doLogin(loginid, password, continute_url);
            }
        }

        public void doLogin(string loginid, string password, string continute_url)
        {

            try
            {
                UserModel user = UserLogin.Login(loginid, password); //用户登录验证................ 
                if (user != null)
                {
                    string token = DateTime.Now.Ticks.ToString(); //加密后的用户信息
                    HttpCookie cookie_user = new HttpCookie("synpay_cas_user", loginid);
                    HttpCookie cookie_pass = new HttpCookie("synpay_cas_data", password);
                    Response.Cookies.Add(cookie_user);
                    Response.Cookies.Add(cookie_pass);
                    Application[token] = user;//缓存token与实际用户信息                
                    Response.Redirect(continute_url + "?token=" + token);//转移
                }
                else
                {
                    InformationMessage = "请输入正确的用户名密码";
                }
            }
            catch (Exception ex)
            {
                InformationMessage = ex.Message;
            }
        }
    }
}
